﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPI_DEMO.Filter
{
    /// <summary>
    /// 异常筛选器
    /// 代码报错
    /// </summary>
    public class GlobalExceptionFilter : IExceptionFilter
    {
        /// <summary>
        ///  日志组件服务
        /// </summary>
        private readonly ILogger<GlobalExceptionFilter> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 有异常需要处理时
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            //记录报错的控制器 和 方法
            var operation = context.HttpContext.Request.RouteValues["controller"] + "/" + context.HttpContext.Request.RouteValues["action"];

            //记录错误日志信息
            _logger.LogError(context.Exception, $"{operation}  Exception:" + context.Exception.Message); //记录错误日志
                                                                                                         //拦截处理

            //如果这个错误没有被处理
            if (!context.ExceptionHandled)
            {
                //返回错误响应
                context.Result = new JsonResult(new
                {
                    status = false,
                    msg = "系统内部错误:" + context.Exception.Message
                });
                //标志错误已经被处理
                context.ExceptionHandled = true;
            }
        }
    }
}
